import { Directive, createElementBlock } from "vue";
import loading from '~/assets/loading.gif'

const directive: Directive = {
    mounted(el, binding) {
        const observe = new IntersectionObserver(([{ isIntersecting }]) => {
            if (!isIntersecting) {
                return
            }
            if (el.src == binding.arg) {
                return;
            }
            const { size, onLoaded, onError, onLoading } = binding.value
            if (size) {
                const width = el.parentElement.offsetWidth;
                const height = size.height / size.width * width
                el.style.width = width + 'px'
                el.style.height = height + 'px'
            } else {
                el.style.width = '100%'
                el.style.height = '100%'
            }


            onLoading?.();
            el.src = loading;
            observe.unobserve(el);
            observe.disconnect();
            setTimeout(() => {
                el.src = binding.arg
            }, (Math.random() + 1) * 200)
            el.loaded = () => {
                onLoaded?.()
            }
            el.onerror = (e: Event) => {
                onError?.(e);
            }

        }, {
            threshold: 0
        })
        observe.observe(el)
    }
}
export default directive